import { forwardRef, useImperativeHandle, useRef, useState } from 'react';

import { useRequest } from 'ahooks';
import {
  Button,
  DatePicker,
  Drawer,
  Form,
  FormProps,
  Input,
  Select,
  Space,
  TreeSelect
} from 'antd';
import { DataNode } from 'antd/es/tree';
import dayjs from 'dayjs';

import { store } from '@/store';

import { orgDeptInfoTreeList } from '@/services/base/bumenguanlibumenxiangguanjiekou';
import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';

import { BizObject } from './';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const treeDict = useRef<Record<number, DataNode>>({});

  const tree = useRequest(async () => {
    treeDict.current = {};

    const res = await orgDeptInfoTreeList();

    const formatData = (data: BASE.OrgDeptInfoVo[]): DataNode[] => {
      const result: DataNode[] = [];

      data.forEach((item) => {
        const node: DataNode = {
          title: item.deptName,
          key: item.id!,
          // @ts-ignore
          value: item.id!,
          children: []
        };

        treeDict.current[item.id!] = node;

        if (item.child && item.child.length > 0) {
          node.children = formatData(item.child);
        }

        result.push(node);
      });

      return result;
    };

    return formatData(res.data || []);
  });

  const userInfo = useRequest(
    async () => {
      const res = await orgUserInfoVoPage({ page: 1, size: 1000 });

      return res?.data?.records;
    },
    {
      refreshDeps: []
    }
  );
  const submit = useRequest(
    async ({ _type, ...values }) => {
      // const query = {
      //   ...values,
      //   beginTime: dayjs(values?.beginTime).format('YYYY-MM-DD HH:mm:ss'),
      //   endTime: dayjs(values?.endTime).format('YYYY-MM-DD HH:mm:ss'),
      //   dutyUserName: userInfo?.data?.filter((item) => item.id === values?.dutyUserId)?.[0]
      //     ?.fullName,
      //   maintainUserName: userInfo?.data?.filter((item) => item.id === values?.maintainUserId)?.[0]
      //     ?.fullName,
      //   cron: '0 ' + values?.cron
      // };
      // if (args?.type === 'edit' && args.rowData) {
      //   query.id = args.rowData.id;
      // }
      // console.log('query', query);
      // await (args?.type === 'edit' ? proRegularWorkUpdate(query) : proRegularWorkAdd(query));
      // args?.onSuccess?.();
      // setOpen(false);
      // store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            const taskDispatchTime = arg.rowData.taskDispatchTime
              ? dayjs(arg.rowData.taskDispatchTime)
              : undefined;
            const requiredCompletionTime = arg.rowData.requiredCompletionTime
              ? dayjs(arg.rowData.requiredCompletionTime)
              : undefined;
            const dispatchDate = arg.rowData.dispatchDate
              ? dayjs(arg.rowData.dispatchDate)
              : undefined;
            // 回填数据
            form.setFieldsValue({
              ...arg.rowData,
              taskDispatchTime,
              requiredCompletionTime,
              dispatchDate
            });
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增任务',
          edit: '编辑任务',
          detail: '任务详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="重要性"
          name="importance"
          rules={[
            {
              required: true,
              message: '请选择重要性'
            }
          ]}
        >
          <Select
            style={{
              width: '100%'
            }}
            allowClear
            placeholder="请选择重要性"
            options={[
              { value: '重要', label: '重要' },
              { value: '普通', label: '普通' },
              { value: '其他', label: '其他' }
            ]}
          />
        </Form.Item>
        <Form.Item
          label="任务内容"
          name="taskContent"
          rules={[
            {
              required: true,
              message: '请输入任务内容'
            }
          ]}
        >
          <Input.TextArea placeholder="请输入任务内容" />
        </Form.Item>
        <Form.Item
          label="工作类型"
          name="taskType"
          rules={[
            {
              required: true,
              message: '请选择工作类型'
            }
          ]}
        >
          <Select
            style={{
              width: '100%'
            }}
            allowClear
            placeholder="请选择工作类型"
            options={[
              { value: '生产早会', label: '生产早会' },
              { value: '其他', label: '其他' }
            ]}
          />
        </Form.Item>
        <Form.Item
          label="任务下发时间"
          name="taskDispatchTime"
          rules={[
            {
              required: true,
              message: '请选择任务下发时间'
            }
          ]}
        >
          <DatePicker style={{ width: '100%' }} showTime placeholder="请选择任务下发时间" />
        </Form.Item>
        <Form.Item
          label="要求完成时间"
          name="requiredCompletionTime"
          rules={[
            {
              required: true,
              message: '请选择要求完成时间'
            }
          ]}
        >
          <DatePicker style={{ width: '100%' }} showTime placeholder="请选择要求完成时间" />
        </Form.Item>
        <Form.Item
          label="安排日期"
          name="dispatchDate"
          rules={[
            {
              required: true,
              message: '请选择安排日期'
            }
          ]}
        >
          <DatePicker style={{ width: '100%' }} placeholder="请选择安排日期" />
        </Form.Item>
        <Form.Item
          label="安排人"
          name="dispatchUserId"
          rules={[
            {
              required: true,
              message: '请选择安排人'
            }
          ]}
        >
          <Select
            style={{ width: '100%' }}
            placeholder="请选择安排人"
            showSearch={true}
            optionFilterProp="label"
            options={
              userInfo?.data?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            }
          />
        </Form.Item>
        <Form.Item
          label="部门"
          name="dutyDeptId"
          rules={[
            {
              required: true,
              message: '请选择部门'
            }
          ]}
        >
          <TreeSelect
            treeData={tree.data}
            treeNodeFilterProp="title"
            showSearch
            placeholder="请选择部门"
            allowClear
            // multiple
          />
        </Form.Item>
        <Form.Item
          label="责任人"
          name="dutyUserId"
          rules={[
            {
              required: true,
              message: '请选择责任人'
            }
          ]}
        >
          <Select
            style={{ width: '100%' }}
            placeholder="请选择责任人"
            showSearch={true}
            optionFilterProp="label"
            options={
              userInfo?.data?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            }
          />
        </Form.Item>

        <Form.Item
          label="任务状态"
          name="status"
          rules={[
            {
              required: true,
              message: '请选择任务状态'
            }
          ]}
        >
          <Select
            style={{
              width: '100%'
            }}
            allowClear
            placeholder="请选择任务状态"
            options={[
              { value: 1, label: '待处理' },
              { value: 3, label: '已完成' }
            ]}
          />
        </Form.Item>
        <Form.Item
          label="执行情况说明"
          name="handleSituation"
          rules={[
            {
              required: true,
              message: '请输入执行情况说明'
            }
          ]}
        >
          <Input.TextArea style={{ width: '100%' }} placeholder="请输入执行情况说明" />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
